// 文件md5加密
// import sparkMd5 from "spark-md5";
import axios from "axios";
import { getToken } from '@ruifox-cms/utils/src/storage'
import { generateUUID } from './tools'
// import { checkMd5 } from './api'

// export function fileMd5(file){
//     let sparkMD5 = new sparkMd5.ArrayBuffer()
//     let reader = new FileReader()
//     reader.readAsArrayBuffer(file)
//     return new Promise((resolve) => {
//         reader.onload = (event) => {
//             //获取文件MD5
//             let str = event.target.result
//             sparkMD5.append(str)
//             let md5_str = sparkMD5.end()
//             checkMd5({md5: md5_str}).then(res => {
//                 res.valid = md5_str
//                 resolve(res)
//             })
//         }
//     })
// }
function uploadAxios(formData,config,url){
    return new Promise((resolve,reject) => {
        const http = axios.create({
            headers: { 
              'X-token': getToken() ,
              'x-timestamp': Date.now(),
            },
        })
        http.post(url, formData, config).then(res => {
            if (res.data) {
                resolve(res)
            } else {
                reject(res)
            }
        }).catch((e) => {
            reject(e)
        })
    })
}
// 单个上传
export function singleUpload(formData,url,onProgress) {
    let config
    if(onProgress){
        config = {
            onUploadProgress: (e) => {
                e.percent = Math.round(
                    (e.loaded * 100) / e.total
                )
                onProgress(e)
            }
        }
    }
    return new Promise((resolve,reject) => {
        uploadAxios(formData,config,url).then(res => {
            resolve(res.data)
        }).catch(e => {
            reject(e)
        })
    })
}
// 分片上传
// export function splitUpload (file,url,onProgress,eachSize) {
//     const uuid = nanoid()
//     // eslint-disable-next-line no-async-promise-executor
//     return new Promise( async (resolve, reject) => {
//         try {
//             const chunks = Math.ceil(file.size / eachSize)
//             const fileChunks = await splitFile(file, eachSize, chunks)
//             for (let i = 1; i <= fileChunks.length; i++) {
//                 let res = await postFile(
//                     {
//                         index: i-1,
//                         total: chunks,
//                         fileName: file.name,
//                         size: file.size,
//                         file: fileChunks[i - 1],
//                         uuid,
//                         eachSize
//                     },
//                     onProgress,
//                     url
//                 )
//                 // 判断返回值是否为字符串，为字符串说明上传完了，返回的是整合后的url
//                 let resFileType = Object.prototype.toString.call(res.data.data).slice(8, -1) === 'String'
//                 if(resFileType){
//                     resolve(res.data)
//                 }
//             }
//         } catch (e) {
//             reject(e)
//         }
//     })
// }
export function splitUpload(file, url, onProgress, eachSize) {
    const uuid = generateUUID()
    // eslint-disable-next-line no-async-promise-executor
    return new Promise(async (resolve, reject) => {
        try {
            const chunks = Math.ceil(file.size / eachSize)
            const fileChunks = await splitFile(file, eachSize, chunks)
            for (let i = 1; i <= fileChunks.length; i++) {
                let retryCount = 0
                while (retryCount < 3) {
                    let res = await postFile(
                        {
                            index: i - 1,
                            total: chunks,
                            fileName: file.name,
                            size: file.size,
                            file: fileChunks[i - 1],
                            uuid,
                            eachSize
                        },
                        onProgress,
                        url
                    )
                    if (res.data.code === 20000) {
                        // 如果返回了整合的url，则不需要再继续上传了
                        if(res.data.data?.url){
                            resolve(res.data.data)
                            onProgress({percent: 100})
                            return
                        }
                        break
                    } else if (res.data.code === 109002) {
                        // 该分片已存在，继续下一个分片的上传
                        break
                    } else {
                        retryCount++
                        if (retryCount === 3) {
                            reject(new Error(`分片 ${i} 上传失败，重试三次后仍未成功。`))
                        }
                    }
                }
            }
        } catch (e) {
            reject(e)
        }
    })
}
const postFile = (param, onProgress, url) => {
    const formData = new FormData()
    for (let p in param) {
        formData.append(p, param[p])
    }
    const config = {
        onUploadProgress: (e) => {
            if(param.index !== param.total -1){ //不是最后一块
                e.percent = Number((e.progress+param.index)*(param.eachSize/param.size)*100)
            }else{ //最后一块
                e.percent = Number(((e.progress)*((param.size - param.eachSize*param.index)/param.size)+param.index*param.eachSize/param.size)*100)
            }
            onProgress(e)
        },
    }
    // 实际上传事件
    return uploadAxios(formData,config,url).then(res => res)
}
const splitFile = (file, eachSize, chunks) => {
    return new Promise((resolve, reject) => {
        try {
            setTimeout(() => {
                const fileChunk = []
                for (let chunk = 0; chunks > 0; chunks--) {
                    fileChunk.push(file.slice(chunk, chunk + eachSize))
                    chunk += eachSize
                }
                resolve(fileChunk)
            }, 0)
        } catch (e) {
            console.error(e)
            reject(new Error('文件切块发生错误'))
        }
    })
}
